package com.assessment.service.impl;

import cn.hutool.core.util.StrUtil;
import com.assessment.common.api.ResultCode;
import com.assessment.common.exception.BusinessException;
import com.assessment.mapper.DepartmentMapper;
import com.assessment.mapper.PositionMapper;
import com.assessment.mapper.SysUserMapper;
import com.assessment.mapper.TeacherMapper;
import com.assessment.model.dto.UserLoginDTO;
import com.assessment.model.entity.Department;
import com.assessment.model.entity.Position;
import com.assessment.model.entity.SysUser;
import com.assessment.model.entity.Teacher;
import com.assessment.model.vo.UserInfoVO;
import com.assessment.service.UserService;
import com.assessment.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpMaJsCode2SessionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private WxCpService wxCpService;

    @Override
    public UserInfoVO wxLogin(UserLoginDTO loginDTO) {
        try {
            String phone = "";
            //用于测试, 传过来的code如果是手机号,  则直接使用
            if (loginDTO.getCode().length() == 11) {
                phone = loginDTO.getCode();
            } else {
                // 1. 通过code获取微信用户会话信息
                WxCpMaJsCode2SessionResult sessionResult = wxCpService.jsCode2Session(loginDTO.getCode());
                String userId = sessionResult.getUserId();
                String corpId = sessionResult.getCorpId();

                // 2. 根据企业微信返回的用户ID查询手机号
                phone = getPhoneFromWx(userId, corpId);
            }


            if (StrUtil.isBlank(phone)) {
                throw new BusinessException(ResultCode.WECHAT_AUTH_ERROR);
            }

            // 3. 根据手机号查询用户
            return getUserByPhone(phone);
        } catch (WxErrorException e) {
            log.error("微信登录失败", e);
            throw new BusinessException(ResultCode.WECHAT_AUTH_ERROR);
        }
    }

    @Override
    public UserInfoVO getUserByPhone(String phone) {
        // 1. 查询教师信息
        Teacher teacher = teacherMapper.findByMobile(phone);
        if (teacher == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        // 2. 查询部门和职位信息
        Department department = departmentMapper.selectById(teacher.getDepartmentId());
        Position position = positionMapper.selectById(teacher.getPositionId());

        // 3. 查询或创建系统用户
        SysUser sysUser = sysUserMapper.findByPhone(phone);
        if (sysUser == null) {
            // 如果系统用户不存在，则创建
            sysUser = new SysUser();
            sysUser.setUsername(phone);
            sysUser.setPassword("$2a$10$IHdyJ7qZSGpkL0oXAF6WB.jJjLUJrYUQMSwj4NR8.GndMTRsOKW7m");
            sysUser.setPhone(phone);
            sysUser.setRealName(teacher.getName());
            sysUser.setEmail(teacher.getEmail());
            sysUser.setAvatar(teacher.getAvatar());
            sysUser.setRole("USER");
            sysUser.setStatus(1);
            sysUserMapper.insert(sysUser);
        }

        // 4. 生成JWT令牌
        String token = JwtUtils.createToken(sysUser.getId(), sysUser.getUsername(), sysUser.getRole());

        // 5. 构建返回的用户信息
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(sysUser.getId());
        userInfoVO.setTeacherId(teacher.getId());
        userInfoVO.setUsername(sysUser.getUsername());
        userInfoVO.setRealName(sysUser.getRealName());
        userInfoVO.setAvatar(sysUser.getAvatar());
        userInfoVO.setPhone(sysUser.getPhone());
        userInfoVO.setRole(sysUser.getRole());
        userInfoVO.setToken(token);

        if (department != null) {
            userInfoVO.setDepartmentId(department.getId());
            userInfoVO.setDepartmentName(department.getName());
        }

        if (position != null) {
            userInfoVO.setPositionId(position.getId());
            userInfoVO.setPositionName(position.getName());
        }

        return userInfoVO;
    }

    /**
     * 从微信获取手机号
     * 这里需要根据实际情况实现，可能需要调用微信API
     */
    private String getPhoneFromWx(String openId, String unionId) {
        // 实际项目中需要通过微信API获取用户绑定的手机号，
        // 这里简化处理，直接模拟返回，实际项目应使用真实的微信API
        log.info("尝试通过openId:{}, unionId:{}获取手机号", openId, unionId);

        // 模拟手机号，实际项目中应该通过微信API获取
        return "13800138001";
    }
}
